package main;

import java.io.DataOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;
import java.util.ArrayList;
import java.util.ConcurrentModificationException;

import javax.sql.rowset.spi.SyncResolver;

import constants.Strings;

public class MessageThread extends Thread {
	Socket socket;
	ObjectInputStream in;
	ObjectOutputStream out;
	String number_id;
	boolean alive = true;
	private ArrayList<String> messages;
	
	public MessageThread(Socket socket, String number_id) {
	    super("Server Thread");
	    this.socket = socket;
	    this.number_id = number_id;
	    messages = new ArrayList<String>();
	    Server.mThreads.add(this);
	}
	
	public void run() {
		do{
		    sendMessage();
		}while(alive);
	}
	
	public synchronized void sendMessage() {
	    try {
	    	DataOutputStream dos = new DataOutputStream(socket.getOutputStream()); 
	    	try{
	    		for (String s : messages)
	            {
	    			Server.log("Sending message to: " + socket);
	            	dos.writeUTF(s);
	            	dos.flush();
	            	messages.remove(s);
	            }
	    	}
	    	catch(ConcurrentModificationException e){
	    		e.printStackTrace();
	    	}
	    } catch (IOException e) {
	        e.printStackTrace();
	    }
	}

	public String getNumber_id() {
		return number_id;
	}

	public void addMessage(String to, String text){
		messages.add("Message" + Strings.SEPERATOR1 + to + Strings.SEPERATOR2 + text);
	}
	
	public void stopThread(){
		alive = false;
	}
}